<script setup>
import { onMounted, onUnmounted } from 'vue'
import { ref } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import { ElMessage } from 'element-plus';
let map = null
const loading = ref(false)
const setMap = (
  startPoint = [117.120128, 36.652069],
  endPoint = [120.382665, 36.066938],
  waypoints = [[121.447755, 37.464551]],
  policyJu = 1
) => {
  window._AMapSecurityConfig = {
    securityJsCode: '774b9fd88be3808898401d4c061b7871'
  }
  AMapLoader.load({
    key: 'f822ba949d3d4638876cf577329d0081', // 申请好的Web端开发者Key，首次调用 load 时必填
    version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ['AMap.Driving'] //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
  })
    .then((AMap) => {
      loading.value=true
      map = new AMap.Map('container', {
        // 设置地图容器id
        viewMode: '3D', // 是否为3D地图模式
        zoom: 17, // 初始化地图级别
        center: [117.120128, 36.652069], // 初始化地图中心点位置
        resizeEnable: true
      })
      const policy = [
        AMap.DrivingPolicy.LEAST_TIME,
        AMap.DrivingPolicy.LEAST_FEE,
        AMap.DrivingPolicy.LEAST_DISTANCE,
        AMap.DrivingPolicy.REAL_TRAFFIC
      ]
      var driving = new AMap.Driving({
        map: map,
        policy: policy[policyJu]
        //panel: 'panel'
      })
      // 将传入的 waypoints 数组转换为 AMap.LngLat 实例数组
      const convertedWaypoints = waypoints.map((point) => new AMap.LngLat(point[0], point[1]))

      // 根据起终点经纬度规划驾车导航路线
      driving.search(
        new AMap.LngLat(startPoint[0], startPoint[1]),
        new AMap.LngLat(endPoint[0], endPoint[1]),
        {
          waypoints: convertedWaypoints
          //waypoints: [new AMap.LngLat(waypoint[0], waypoint[1])]
        },
        function (status) {
          // result 即是对应的驾车导航信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
          if (status === 'complete') {
            loading.value=false
            // console.log('绘制驾车路线完成')
            ElMessage.success('驾车路线绘制成功')
          } else {
            loading.value=false
            //console.log('获取驾车数据失败：' + result)
            ElMessage.error('获取驾车数据失败，请重试' )
          }
        }
      )
    })
    .catch((e) => {
      console.log(e)
    })
}
onMounted(() => {
  setMap()
})

onUnmounted(() => {
  map?.destroy()
})
const startValue = ref('')
const endValue = ref('')
const value1 = ref([])
const policyValue = ref('最短时间')
const options = [
  {
    id: '1',
    value: {
      jingdu: 117.120128,
      weidu: 36.652069
    },
    label: '济南'
  },
  {
    id: '2',
    value: {
      jingdu: 120.382665,
      weidu: 36.066938
    },
    label: '青岛'
  },
  {
    id: 3,
    value: {
      jingdu: 121.447755,
      weidu: 37.464551
    },
    label: '烟台'
  },
  {
    id: 4,
    value: {
      jingdu: 119.161721,
      weidu: 36.707668
    },
    label: '潍坊'
  },
  {
    id: 5,
    value: {
      jingdu: 118.356464,
      weidu: 35.103771
    },
    label: '临沂'
  },
  {
    id: 6,
    value: {
      jingdu: 118.054994,
      weidu: 36.813787
    },
    label: '淄博'
  },
  {
    id: 7,
    value: {
      jingdu: 115.985238,
      weidu: 36.455857
    },
    label: '聊城'
  },
  {
    id: 8,
    value: {
      jingdu: 116.359244,
      weidu: 37.436492
    },
    label: '德州'
  },
  {
    id: 9,
    value: {
      jingdu: 117.086963,
      weidu: 36.201784
    },
    label: '泰安'
  },
  {
    id: 10,
    value: {
      jingdu: 117.970731,
      weidu: 37.382687
    },
    label: '滨州'
  },
  {
    id: 11,
    value: {
      jingdu: 118.674633,
      weidu: 37.433992
    },
    label: '东营'
  },
  {
    id: 12,
    value: {
      jingdu: 115.479646,
      weidu: 35.234309
    },
    label: '菏泽'
  },
  {
    id: 13,
    value: {
      jingdu: 122.120519,
      weidu: 37.513315
    },
    label: '威海'
  },
  {
    id: 14,
    value: {
      jingdu: 117.323759,
      weidu: 34.810858
    },
    label: '枣庄'
  },
  {
    id: 15,
    value: {
      jingdu: 119.52685,
      weidu: 35.416912
    },
    label: '日照'
  },
  {
    id: 16,
    value: {
      jingdu: 116.587116,
      weidu: 35.415117
    },
    label: '济宁'
  }
]
const policyOptions = [
  {
    value: 'LEAST_TIME',
    label: '最少时间'
  },
  {
    value: 'LEAST_FEE',
    label: '最少费用'
  },
  {
    value: 'LEAST_DISTANCE',
    label: '最短距离'
  },
  {
    value: 'REAL_TRAFFIC',
    label: '躲避拥堵'
  }
]

const submit = () => {
  // 使用 split() 方法将字符串分割成数组
  const startArray = startValue.value.split(',')
  // 去除数组元素中的空白字符
  const trimmedStartArray = startArray.map((item) => item.trim())
  //console.log(trimmedStartArray)

  const endArray = endValue.value.split(',')
  const trimmedEndArray = endArray.map((item) => item.trim())
  if (!trimmedStartArray[0] || !trimmedEndArray[0]) {
    ElMessage.error('请输入出发地或目的地')
    return 
  }
  if(sliderValue.value[0]>sliderValue.value[1]){
    sliderValue.value[0]=0
    ElMessage.error('请输入正确的预算范围')
    return
  }
  if(typeof sliderValue.value[0]!=='number'||typeof sliderValue.value[1]!=='number'){
    ElMessage.error('请输入正确的预算范围')
    return 
  }
  else {
    // 获取proxy中target的值
    const value = JSON.parse(JSON.stringify(value1.value))
    //console.log(value)

    const waypoints = value.map((item) => {
      const wayArray = item.split(',')
      return wayArray.map((item) => item.trim())
    })
    //console.log(policyValue.value)

    // 调用 setMap 函数并传递参数
    if (policyValue.value === 'LEAST_FEE') {
      setMap(trimmedStartArray, trimmedEndArray, waypoints, 2)
      return
    } else if (policyValue.value === 'LEAST_DISTANCE') {
      setMap(trimmedStartArray, trimmedEndArray, waypoints, 3)
      return
    } else if (policyValue.value === 'REAL_TRAFFIC') {
      setMap(trimmedStartArray, trimmedEndArray, waypoints, 4)
      return
    }
    setMap(trimmedStartArray, trimmedEndArray, waypoints, 1)
    return
  }
}
const sliderValue = ref([1, 1000])
const handleInput=()=>{
  if(sliderValue.value[1]<0||sliderValue.value[0]<0){
    ElMessage.error('请输入正确的预算范围')
  }
  else if(sliderValue.value[1]>10000||sliderValue.value[0]>10000){
    ElMessage.warning('请不要铺张浪费')
  }
}

</script>

<template>
  <div id="container" v-loading="loading" style="margin-top: 450px;"></div>
  <div class="pink-box" style="margin-top: 450px;">
    <strong class="start">出发地</strong>
    <el-select v-model="startValue" placeholder="济南" size="large" style="width: 240px">
      <el-option
        v-for="item in options"
        :key="item.id"
        :label="item.label"
        :value="item.value.jingdu + ',' + item.value.weidu"
      />
    </el-select>
    <strong class="end">目的地</strong>
    <el-select v-model="endValue" placeholder="青岛" size="large" style="width: 240px">
      <el-option
        v-for="item in options"
        :key="item.id"
        :label="item.label"
        :value="item.value.jingdu + ',' + item.value.weidu"
      />
    </el-select>
    <strong class="way">途径地</strong>
    <el-select class="elect-way" v-model="value1" multiple placeholder="烟台" style="width: 240px">
      <el-option
        v-for="item in options"
        :key="item.id"
        :label="item.label"
        :value="item.value.jingdu + ',' + item.value.weidu"
      />
    </el-select>
    <strong class="start">选择出行策略</strong>
    <el-select
      class="start-way"
      v-model="policyValue"
      placeholder="最少时间"
      size="large"
      style="width: 240px"
    >
      <el-option
        v-for="item in policyOptions"
        :key="item.id"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
    <strong class="price">总预算（元）</strong>
    <div class="slider-demo-block">
      <el-slider v-model="sliderValue" step="10" range :max="10000" />
    </div>
    <el-input
      class="left-input"
      @input="handleInput"
      v-model="sliderValue[0]"
      maxlength="5"
      minlength="1"
      style="width: 100px"
      placeholder="最小值"
      clearable
    />
    <el-input
      class="right-input"
      v-model="sliderValue[1]"
      maxlength="5"
      minlength="1"
      style="width: 100px"
      placeholder="最大值"
      clearable
    />

    <el-button class="submit-button" type="primary" size="large" @click="submit">提交</el-button>
  </div>
</template>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
#container {
  position: absolute;
  width: 700px;
  height: 600px;
  right: 120px;
  top: 50%;
  transform: translateY(-50%);
}
.pink-box {
  position: absolute;
  height: 600px;
  width: 500px;
  left: 130px;
  /* background-color: pink; */
  top: 50%;
  transform: translateY(-50%);
}
.el-select {
  font-size: 16px;
  font-weight: 700;
  gap: 6px;
  line-height: 14px;
  min-height: 14px;
  padding: 15px 10px;
  width: 150px !important;
  margin-left: 20px;
}
.elect-way {
  width: 388px !important;
}
.start-way {
  width: 338px !important;
}
strong {
  position: relative;
  display: inline-block;
  margin-top: 20px;
  margin-left: 20px;
  margin-bottom: 10px;
}
.submit-button {
  position: absolute;
  left: 20px;
  bottom: 20px;
}
.price {
  display: block;
  margin-top: 210px;
  margin-bottom: 5px;
}
.slider-demo-block {
  max-width: 460px;
  display: flex;
  align-items: center;
}
.slider-demo-block .el-slider {
  margin-left: 20px;
}
.left-input {
  margin-left: 20px;
}
.right-input {
  margin-left: 240px;
}
</style>
